<?php

/**
 * Created by PhpStorm.
 * User: Yieong
 * Date: 16/4/6
 * Time: 上午9:49
 */
class BroadcastService extends Service{

    public static function indexHeader(){
        return array(
        		'id'                => array('text' => '广播ID', 'rule' => 'int'),
        		'server_name'       => array('text' => '同步服务器','width' => '300px'),
                'message_type'      => array('text' => '消息类型'),
        		'start_time'        => array('text' => '开始时间'),
        		'end_time'          => array('text' => '结束时间'),
        		'number'            => array('text' => '次数'),
        		'frequency'         => array('text' => '间隔时间'),
                'message_content'   => array('text' => '消息内容','width' => '350px'),
        		'create_user'       => array('text' => '添加人'),
        		'create_time'       => array('text' => '创建时间'),
        		'synchro_time'       => array('text' => '同步时间'),
                //'action'            => array('text' => '操作')
        );
    }

    /**
     * 广播列表
     * @param $params
     */
    public static function indexData($params){
    	$user = AccAuth::me();
    	if($user['IsAdmin'] != 1 && $user['AddBy'] != 1){ //超级管理员和由超级管理员创建的账号能看到所有数据
    		$params['create_user'] = $user['UserID'];
    	}
    	
    	$modBroadcast = new ModBroadcast();
        $result = $modBroadcast->select($params);
    
    	$typeDict = self::typeList();
    	$userList = self::userList();
    	foreach($result as &$v){    		
    		$type = '';
    		$message_type_array = explode(',', $v['message_type']);
    		foreach ($message_type_array as $key=>$val){
    			$type = $type.',&nbsp;'.$typeDict[$val].'&nbsp;';
    		}
    		$type = substr($type, 1);
    		
    		$v['start_time'] = $v['start_time'] == 0? '不限':date('Y-m-d H:i:s', $v['start_time']);
    		$v['end_time'] = $v['end_time'] == 0? '不限':date('Y-m-d H:i:s', $v['end_time']);
    		$v['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
    		$v['message_type']   = $type;
    		$v['message_content'] = '<div style="white-space:normal;">'.$v['message_content'].'</div>';
    		$v['action']         = ' <a href="'.PubFunc::buildUrl('/oss/?r=broadcast/delete').'&id='.$v['id'].'" confirm="是否要删除该条服信息?">删除</a>';
    		$v['create_user'] = $userList[$v['create_user']];
    		
    		$id = $v['id'];   		
    		if($v['synchro_time'] == ''){
    			$v['server_name'] = '<a href="JavaScript:void(0);" name="synchro_one" data-id="'.$v['id'].'" >同步</a>';
    			$v['synchro_time'] = '未同步';
    			$checkbox = '<input value="'.$v['id'].'" name="id" type="checkbox">&nbsp;&nbsp;';
    			
    		}else{
    			$v['server_name'] = '<div style="white-space:normal;">'.$v['server_name'].'</div>';
    			$v['synchro_time'] = date('Y-m-d H:i:s', $v['synchro_time']);
    			$checkbox = '<input value="'.$v['id'].'" name="id" disabled="disabled" type="checkbox">&nbsp;&nbsp;';
    		}
    		$v['id'] = $checkbox.$v['id'];
    		
    	}
    	unset($v);
    
    	return $result;
    }
    
    public static function doAdd($params){
    	if(PubFunc::checkEmpty($params, array( 'type', 'content','number','frequency'))){
    		return array('state' => false, 'msg' => '缺少必要参数.');
    	}

    	//$server_array = explode('-', $params['server']);
    	//$params['server'] = $server_array[0];
    	//请求接口，接口成功再入库
    	//$result = self::send($params);
    	$result['state'] = true;
     	if($result['state']){
    		$user = AccAuth::me();
    		$modBroadcast = new ModBroadcast();
    		 
    		$type = implode(',', $params['type']);
    		
    		$start_time = $params['start_time'] == ''? 0 : strtotime($params['start_time']);
    		$end_time = $params['end_time'] == ''? 0 : strtotime($params['end_time']);
    		 
    		$modBroadcast->platform      = 'test';
    		$modBroadcast->game          = $params['g'];
    		//$modBroadcast->server_id  = $server_array[0];
    		//$modBroadcast->server_name   = $server_array[1];
    		$modBroadcast->message_type    = $type;
    		$modBroadcast->message_content       = $params['content'];
    		$modBroadcast->create_user   = $user['UserID'];
    		$modBroadcast->create_time   = time();
    		$modBroadcast->update_user   = $user['UserID'];
    		$modBroadcast->update_time   = time();
    		$modBroadcast->start_time = $start_time;
    		$modBroadcast->end_time = $end_time;
    		$modBroadcast->number = $params['number'];
    		$modBroadcast->frequency = $params['frequency'];
    		
    		$result = $modBroadcast->save();
    		return array('state' => $result, 'msg' =>'添加成功');
    	}else{
    		return array('state' => false, 'msg' => $result['msg']);
    	}	
    	
    }
    
    public static function delete($id){
    	if(empty($id)) return false;
    
    	$modBroadcast = new ModBroadcast();
    	$modBroadcast->deleteByPk($id);
    	return true;
    }
    
   
    /**
     * 消息类型
     * @return array
     */
    public static function typeList(){
        return array(
            '9' => '顶部滚动',
            '1' => '系统消息'
        );
    }
    
    
    /**
     * 发送广播公告
     */
    public static function send($params){
    	unset($params['m']);
    	unset($params['g']);
    	unset($params['p']);
    	
    	$accessory = array();
    	foreach ($params['type'] as $key=>$val){
    		$accessory['item'][] = array(
    				'type'    => $val,
    		);
    	}
    	$type = json_encode($accessory);
    	$params['type']  = $type;
    
    	$api = new ApiService($params['server']);
    	unset($params['server']);
    	return $api->sendBroadcast($params);
    }
    
    
    public static function synchro($ids,$servers){
    	$modBroadcast = new ModBroadcast();
    	$serverList = PubServer::getOptions($platform, $game, 'id');
    	
    	$ids_array = explode(',', $ids);
    	
    	$server_array = explode(',', $servers);
    	$server_array = array_unique($server_array);
    	
    	$info_res = '';
    	foreach ($ids_array as $key=>$val){    		
    		$obj = $modBroadcast->findByPk($val);
    		$info = $obj->getAttributes();
    		$params = array();
    		$params['content'] = $info['message_content'];
    		$params['type'] = explode(',',$info['message_type']);
    		$params['start_time'] = intval($info['start_time']);
    		$params['end_time'] = intval($info['end_time']);
    		$params['times'] = intval($info['number']);
    		$params['range'] = intval($info['frequency']);
    		$info_res .= '广播ID为 <font color="red">'.$info['id'].'</font>';
    		$server_id = '';
    		$server_name = '';
    		foreach ($server_array as $key1=>$val1){
    			$params['server'] = $val1;
    			$result = self::send($params);
    			//$result['state'] = true;
    			if($result['state']){
    				$server_id .= ','.$val1;
    				$server_name .= ','.$serverList[$val1];
    				$info_res .= ' 发送服务器 <font color="red">'.$serverList[$val1].' </font>成功<br/>';
    			}else{
    				$info_res .= ' 发送服务器 <font color="red">'.$serverList[$val1].' </font>失败，失败原因'.$result['msg'].'<br/>';
    			}
    		}
    		
    	    if($server_id != '' && $server_name != ''){
    			$server_id = substr($server_id, 1);
    			$server_name = substr($server_name, 1);
    			$update = array();
    			$update['server_id']     = $server_id;
    			$update['server_name']     = $server_name;
    			$update['synchro_time']  = time();
    			$modBroadcast->updateByPk($info['id'], $update);
    		}
    	}
    	return $info_res;
    	
    }

}